package com.example.quiz;

import java.io.ByteArrayOutputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.quiz.model.HttpManager;
import com.example.quiz.model.PacoteRequisicao;

public class ElaborarPergunta extends Activity {
	
	private Tarefa tarefa;
	private ProgressBar pb;
	private HttpManager hm = new HttpManager();
	private String persistencia = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.elaborar_pergunta);
		
		pb = (ProgressBar) findViewById(R.id.pbElaborar);
		pb.setVisibility(View.INVISIBLE);
		
		byte[] byteArray = getIntent().getByteArrayExtra("foto");
		final Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
		ImageView iv = (ImageView) findViewById(R.id.ivE);
		iv.setImageBitmap(bm);
		final EditText etP = (EditText) findViewById(R.id.etPergunta);
		final EditText etR = (EditText) findViewById(R.id.etResposta);
		final EditText etA1 = (EditText) findViewById(R.id.etAlternativa1);
		final EditText etA2 = (EditText) findViewById(R.id.etAlternativa2);
		final EditText etA3 = (EditText) findViewById(R.id.etAlternativa3);
		final EditText etA4 = (EditText) findViewById(R.id.etAlternativa4);
		
		final Validador check = new Validador();
		
		Button btnSalvar = (Button) findViewById(R.id.btnSalvarPergunta);
		btnSalvar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(check.validarET(etP,5) && check.validarET(etR,1) && check.validarET(etA1,1) && check.validarET(etA2,1)){	
					
					tarefa = new Tarefa();
					pb.setVisibility(View.VISIBLE);						
					tarefa = new Tarefa();
					PacoteRequisicao pacote = new PacoteRequisicao();
					pacote.setMethod("POST");
					pacote.setUri("http://192.168.25.18:8080/QuizServer/ServletElaborarQuiz");
					pacote.setParametro("pergunta", etP.getText().toString());
					pacote.setParametro("resposta", etR.getText().toString());
					pacote.setParametro("alternativas", etA1.getText().toString()+"|"+etA2.getText().toString()+"|"+etA3.getText().toString()+"|"+etA4.getText().toString());
					pacote.setParametro("foto", bitmapToString(bm));					
					
					tarefa.execute(pacote);	
					
					startActivity(new Intent(ElaborarPergunta.this, OrigemFoto.class));
				}else{
					Toast.makeText(getApplicationContext(), "Pelo menos 5 caracteres para pergunta e 1 para resposta(Minimo de duas alternativas)", Toast.LENGTH_SHORT).show();
				}
			}

			
		});
		
		
		Button btnVoltar = (Button) findViewById(R.id.btnVoltarElaborar);
		btnVoltar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(ElaborarPergunta.this, OrigemFoto.class));
			}
		});
		
	}
	private String bitmapToString(final Bitmap bm) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();		
		bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);		
		byte[] byteArray = stream.toByteArray();		
		String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
		return encodedImage;
	}
	private class Tarefa extends AsyncTask<PacoteRequisicao, String, String>{

		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected String doInBackground(PacoteRequisicao... params) {
			
			try {
				JSONObject json = new JSONObject(hm.getData(params[0]));
				persistencia = json.getString("message"); 
//				Log.i("logquiz",json.getString("message"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {			
			pb.setVisibility(View.INVISIBLE);	
				
			if(Boolean.parseBoolean(persistencia)){
				Toast.makeText(getApplicationContext(), "Quiz armazenado com sucesso", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(getApplicationContext(), "Falha ao persistir o quiz", Toast.LENGTH_SHORT).show();
			}			
		}
		
		@Override
		protected void onProgressUpdate(String... values) {
		}
	}
}
